<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/19
 * 描述:
 */

namespace app\result;

use app\model\AppVersion;
use app\model\UpdateLog;
use app\model\UploadFilesLog;

class UpdateResult extends BaseResult
{
    //落地页
    public function index($args)
    {
        $platform = strtolower($args['platform'] ?? '');
        if ($platform === 'windows') {
            $platform = 'android';
        }
        $where = ['platform' => $platform, 'status' => 1];
        $where['wgt_flag'] = 0;//非热更新包 这里都是大更新
        $where['is_test'] = 0;
        $data = (new AppVersion())->data_get($where, '*', 'id desc');
        $setting = (new SettingResult())->get('appIndex');
        !empty($setting['value']) && $setting['value'] = htmlspecialchars_decode($setting['value']);
        return self::success_return('success', [
            'app' => $data ?? null,
            'html' => $setting['value'] ?? ''
        ]);// 落地页
    }

    //检查更新
    public function check($args, $user_id = 0)
    {
        bs_log($args, 'check_update', 'check_update.log');
        $ffff = trim($args['ffff'] ?? '');//来自落地页
        $platform = strtolower($args['platform'] ?? '');
        $version = $args['version'] ?? '';
        $where = ['platform' => $platform, 'status' => 1];
        $where['wgt_flag'] = 0;//非热更新包 这里都是大更新
        $is_tester = false;
        if (in_array($user_id, [88909, 88923, 88925])) {
            unset($where['wgt_flag']);
            $is_tester = true;
        }
        if ($ffff === 'index') {
            $where['is_test'] = 0;
        }
        $data = (new AppVersion())->data_get($where, '*', 'id desc');
        if (empty($data)) {
            $args['u'] = $user_id;
            return self::error_return('暂无更新', $args);
        }
        if ($data['is_test'] == 1) {
            //自己的账号
            if ($is_tester) {
                $need_update = $this->is_need_update($version, $data['version']);
                if (!$need_update) {
                    return self::error_return('暂无更新', [
                        $data,
                        $args
                    ]);
                }
                return self::success_return('success', [
                    'version' => $data['version'],
                    'url' => $data['url'],
                    'log' => '最新版本：' . $data['version'] . "\r\n" . $data['tips'],
                    'force' => $data['is_force'] ?? 0,
                    'args' => $args
                ]);
            } else {
                return self::error_return('暂无更新', 123);
            }
        }
        if (empty($version)) {
            return self::success_return('success', $data);// 落地页
        }
        $need_update = $this->is_need_update($version, $data['version']);
        if (!$need_update) {
            return self::error_return('暂无更新', [
                'data' => $data,
                'args' => $args
            ]);
        }

        $log = '最新版本：V' . $data['version'] . "\r\n" . $data['tips'];
        $size = (new UploadFilesLog())->get_value(['full_url' => $data['url']], 'size');
        if ($size) {
            $log .= "\r\n文件大小：" . (ToolsResult::format_bytes($size));
        }
        return self::success_return('success', [
            'version' => $data['version'],
            'url' => $data['url'],
            'log' => $log,
            'force' => $data['is_force'] ?? 0,
            'args' => $args,
            'user_id' => $user_id
        ]);
    }

    public function web_version($args)
    {
        $platform = $args['type'] ?? '';
        $version = $args['version'] ?? '1000';

        $data = (new AppVersion())->data_get(['platform' => $platform, 'status' => 1], '*', 'version desc');
        if (empty($data)) {
            return self::error_return('暂无更新', $args);
        }
        $need_update = $this->is_need_update($version, $data['version']);
        if (!$need_update) {
            return self::error_return('暂无更新', $args);
        }
        return self::success_return('success', [
            'version' => $data['version'],
            'url' => $data['url'],
            'log' => '最新版本：' . $data['version'] . "\r\n" . $data['tips'],
            'force' => $data['is_force'] ?? 0,
            'args' => $args
        ]);
    }

    /**
     * 版本对比
     * @param string $v1 入参的版本
     * @param string $v2 这里配置的版本，最新版
     * @return bool
     */
    private function is_need_update($v1, $v2): bool
    {
        $version1 = explode('.', $v1);
        $version2 = explode('.', $v2);
        for ($i = 0; $i < count($version1); $i++) {
            if ($version1[$i] < $version2[$i]) {
                return true;
            } elseif ($version1[$i] > $version2[$i]) {
                return false;
            }
        }
        return false;
    }


    public function wgt_version($args = []): array
    {
        bs_log($args, 'wgt_version', 'wgt_version.log');
        $appWgtVersion = trim($args['appWgtVersion'] ?? "");
        $currenWgtVersion = $args['app_current_wgt_version'] ?? [];//多个版本
        if (empty($currenWgtVersion)) {
            $currenWgtVersion = [0];
        }
        if (empty($appWgtVersion)) {
            return self::error_return('没有资源包需要更新');
        } elseif (is_string($currenWgtVersion)) {
            $currenWgtVersion = @json_decode($currenWgtVersion, true);
        }
        if (!is_array($currenWgtVersion)) {
            return self::error_return('参数错误');
        }
        $currenWgtVersion = max($currenWgtVersion);
        $version = $args['appVersion'] ?? '';
        $platform = $args['platform'] ?? '';
        if (empty($platform)) {
            return self::error_return('平台参数错误');
        }
        $data = (new AppVersion())->data_list([
            ['platform', '=', strtolower($platform)],
            ['version', '=', $version],
            ['status', '=', 1],
            ['wgt_flag', '=', 1],
            ['wgt_version', '>', $currenWgtVersion]
        ], '*', 'wgt_version asc', 1, 5);
        if (empty($data[0])) {
            return self::error_return('暂无更新');
        }
        return self::success_return('success', [
            'info_list' => $data->toArray(),
            'args' => $args
        ]);
    }
}
